package com.base.common.util;

import com.base.common.BaseConstants;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Title 日期与时间戳的相互转换，获取当前时间戳（精确到秒），
 */
public class DateUtil {
    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的10位整型数据
     * @param format
     * @return
     */
    public static String timeStamp2Date(Integer seconds, String format) {
        if (seconds == null || seconds == 0 || seconds.equals("null")) {
            return "";
        }
        if (format == null || format == "") {
            format = BaseConstants.YYYY_MM_DD_HH_MM_SS;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String seconds_str = seconds.toString() + "000";
        return sdf.format(new Date(Long.parseLong(seconds_str)));
    }

    /**
     * 日期格式字符串转换成时间戳（精确到秒）
     *
     * @param date_str 字符串日期
     * @param format   如：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Integer date2TimeStamp(String date_str, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return (int) (sdf.parse(date_str).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 取得当前时间戳（精确到秒）
     *
     * @return
     */
    public static Integer timeStamp() {
        long time = System.currentTimeMillis();
        Integer t = (int) (time / 1000);
        return t;
    }

    /**
     * 取得某年某月有多少天
     *
     * @param year
     * @param month
     * @return
     */
    public static int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0); //输入类型为int类型
        return c.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);

        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {//同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                {
                    timeDistance += 366;
                } else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {//不同年
            return day2 - day1;
        }
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * 当前时间 to 字符串
     * @param format
     * @return
     */
    public static String date2String(String format) {
        return date2String(new Date(), format);
    }

    /**
     * 字符串yyyy-MM-dd HH:mm:ss
     * @param date
     * @return
     */
    public static String date2StringTime(Date date) {
        return date2String(date, BaseConstants.YYYY_MM_DD_HH_MM_SS);
    }

    /**
     * 字符串yyyy-MM-dd HH:mm:ss
     * @param date
     * @return
     */
    public static String date2StringDate(Date date) {
        return date2String(date, BaseConstants.YYYY_MM_DD);
    }

    /**
     * 日期格式化
     * @param date
     * @param format
     * @return
     */
    public static String date2String(Date date,String format) {
        if (null == date) {
            return BaseConstants.EMPTY_STRING;
        }
        return DateFormatUtils.format(date, format);
    }

    /**
     * 字符时间转化成日期
     * @param source
     * @return
     */
    public static Date String2date(String source) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        source = source.trim();
        try {
            SimpleDateFormat formatter;
            if (source.contains("-")) {
                if (source.contains(":")) {
                    if(source.length() == 19) {
                        formatter = new SimpleDateFormat(BaseConstants.YYYY_MM_DD_HH_MM_SS);
                    } else{
                        formatter = new SimpleDateFormat(BaseConstants.YYYY_MM_DD_HH_MM);
                    }
                } else {
                    if(source.length() == 13) {
                        formatter = new SimpleDateFormat(BaseConstants.YYYY_MM_DD_HH);
                    } else if(source.length() == 10){
                        formatter = new SimpleDateFormat(BaseConstants.YYYY_MM_DD);
                    } else if(source.length() == 7){
                        formatter = new SimpleDateFormat(BaseConstants.YYYY_MM);
                    } else if(source.length() == 4){
                        formatter = new SimpleDateFormat(BaseConstants.YYYY);
                    } else {
                        formatter = new SimpleDateFormat(BaseConstants.YY);
                    }
                }
                Date dtDate = formatter.parse(source);
                return dtDate;
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", source));
    }

    /**
     * 字符时间转化成日期
     * @param source
     * @param format
     * @return
     */
    public static Date String2date(String source, String format) {
        if (StringUtils.isBlank(source)) {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        try {
            return formatter.parse(source);
        } catch (ParseException e) {
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
    }
}
